package cn.qyd.threadsignal;

import java.util.concurrent.Exchanger;

/**
 * @author 邱运铎
 * Exchanger 多用作于多线程之间协作的工具类
 * @date 2024-03-19 12:25
 */
public class ExchangerTwoDemo {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(() -> {
            try {
                String data1 = "data1";
                System.out.println(Thread.currentThread().getName() + " 正在将data1: " + data1 + " 交换出去。。。");
                Thread.sleep(1000);
                String data2 = exchanger.exchange(data1);
                System.out.println(Thread.currentThread().getName() + " 交换到了数据data2： " + data2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"Thread 1").start();

        new Thread(() -> {
            try {
                String data1 = "data2";
                System.out.println(Thread.currentThread().getName() + " 正在将data1: " + data1 + " 交换出去。。。");
                Thread.sleep(2000);
                String data2 = exchanger.exchange(data1);
                System.out.println(Thread.currentThread().getName() + " 交换到了数据data2： " + data2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"Thread 2").start();
    }
}
